package com.yc.project1.Dao;

import com.yc.project1.bean.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author zwei
 * @create 2024-08-07 16:19
 */
@Repository
public class AccountDaoImpl implements AccountDao{
    //         注入数据源
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private CacheManager cacheManager;

    @Override
    public void getCache(int accountid) {
        Cache usersCache = cacheManager.getCache("users");
        if (usersCache != null) {
            // 获取缓存中的值
            Account cachedValue = usersCache.get(accountid, Account.class);
            if (cachedValue != null) {
                System.out.println("users中的键为"+accountid+"的值为" + cachedValue);
            } else {
                System.out.println("users中的"+accountid+"键无对应的值");
            }
        } else {
            System.out.println("无users缓冲区");
        }
    }
    @Override
    @Cacheable(cacheNames = "users",key = "#accountid")  // cacheNames缓存的名称    key  缓存的键
    public Account findById(int accountid) {
        String sql="select * from accounts where accountid=?";
        Account account=jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
            Account account1=new Account();
            account1.setAccountid(rs.getInt(1));
            account1.setBalance(rs.getDouble(2));
            return account1;
        },accountid);
        if (account==null){
            throw new RuntimeException("未找到该用户");
        }
        return account;
    }
    @Override
    @CacheEvict(cacheNames = "users",key = "#accountid")
//    @CacheEvict( value= "users",key = "#accountid")
    public void delect(int accountid) {
        System.out.println(accountid+"所对应的缓存已删除");
    }

    @Override
    @CachePut(cacheNames = "users",key = "#accountid")
    public Account update(int accountid) {
        String sql="update accounts set balance=? where accountid=?";
        double money=findById(accountid).getBalance()+100;
        jdbcTemplate.update(sql,money,accountid);
        Account account = findById(accountid);
        return account;
    }
}
